package com.kfm.jdbc.day0330;

import java.io.*;

public class FileCutter {

    public static void main(String[] args) {
        FileCutter cutter = new FileCutter();
        int count = cutter.split(new File("D:\\temp\\kxmrg.mp4"), 1024 * 1024 * 11, new File("d:\\io\\cutter\\"));
        System.out.println("分割后的文件数量：" + count);
    }



    /**
     * 分割文件
     * @param original 原始文件
     * @param size 分割大小
     * @param directory 分割后的文件存放目录
     * @return 分割后的文件数量
     */
    public int split(final File original, final long size, final File directory){
        // 1. 读取文件
        if (original == null || !original.exists() || !original.isFile() || size <= 0 || directory == null) {
            throw new IllegalArgumentException("参数不合法");
        }
        // 判断目录是否存在，不存在则创建
        if (!directory.exists()){
            directory.mkdirs();
        }
        // 文件数量
        int count = 0;
        try (FileInputStream fis = new FileInputStream(original);){
            // 单文件大小 小于 每次读取的上限 (10M)
            if (size < 1024 * 1024 * 10){
                byte[] bytes = new byte[(int) size];
                int len = -1;

                while ( (len = fis.read(bytes)) != -1){
                    FileOutputStream fos = new FileOutputStream(directory + File.separator + original.getName() + ".part" + ++count);
                    fos.write(bytes, 0, len);
                    fos.close();
                }
            } else {
                // 写 11M 的文件，每次读 10M
                byte[] bytes = new byte[1024 * 1024 * 10];

                while (fis.available() > 0){
                    //  写单个文件得读多次
                    FileOutputStream fos = new FileOutputStream(directory + File.separator + original.getName() + ".part" + ++count);
                    int target = 0;
                    // 判断剩余的字节数是否大于 单文件size
                    if (fis.available() > size){
                        target = (int) size;
                    } else {
                        target = fis.available();
                    }
                    while (target > 0){
                        int length = -1;
                        if (target > bytes.length){
                            length = fis.read(bytes);
                        } else {
                            length = fis.read(bytes, 0, target);
                        }
                        target -= length;
                        fos.write(bytes, 0, length);
                    }
                    fos.close();
                }


            }


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return count;
    }
}
